package org.zjx.util;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class WindowLayoutHelper {

    // 获取当前屏幕的宽高
    public static Dimension getScreenSize() {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        return toolkit.getScreenSize();
    }

    // 计算最多可以放多少个窗口
    public static int calculateMaxWindows(int width, int height) {
        // 获取屏幕宽高
        Dimension screenSize = getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        // 计算可以放多少列和多少行
        int columns = screenWidth / width;
        int rows = screenHeight / height;

        // 最大窗口数量
        return columns * rows;
    }

    // 计算每个窗口的 Rectangle，保证窗口均匀排列，不遮挡，并且有间隔
    public static List<Rectangle> calculateWindowPositions(int totalWindows, int width, int height) {
        // 获取屏幕宽高
        Dimension screenSize = getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        // 计算最大可以容纳的列数和行数
        int maxColumns = screenWidth / width;
        int maxRows = screenHeight / height;

        // 窗口排列列数和行数
        int columns = Math.min(maxColumns, (int) Math.ceil(Math.sqrt(totalWindows)));
        int rows = (int) Math.ceil((double) totalWindows / columns);

        // 计算每个窗口之间的水平和垂直间隔
        int totalHorizontalSpacing = screenWidth - columns * width;
        int totalVerticalSpacing = screenHeight - rows * height;

        // 计算间隔（分配剩余的空间）
        int horizontalSpacing = totalHorizontalSpacing / (columns + 1);
        int verticalSpacing = totalVerticalSpacing / (rows + 1);

        // 创建窗口的布局
        List<Rectangle> windowRectangle = new ArrayList<>();
        for (int i = 0; i < totalWindows; i++) {
            // 计算当前窗口的行和列
            int row = i / columns;
            int col = i % columns;

            // 计算每个窗口的位置，考虑间隔
            int x = col * width + (col + 1) * horizontalSpacing;
            int y = row * height + (row + 1) * verticalSpacing;

            // 检查窗口是否超出屏幕范围
            if (x + width <= screenWidth && y + height <= screenHeight) {
                // 创建一个 Rectangle 对象表示窗口的位置
                windowRectangle.add(new Rectangle(x, y, width, height));
            }
        }

        return windowRectangle;
    }

    public static void main(String[] args) {
        int totalWindows = 6; // 假设需要排列6个窗口

        // 计算窗口的位置
        List<Rectangle> windowPositions = calculateWindowPositions(totalWindows, 1200, 600);

        // 打印每个窗口的位置和大小
        for (Rectangle rect : windowPositions) {
            System.out.println("窗口位置: " + rect.toString());
        }

        // 计算最大可以放多少个窗口
        int maxWindows = calculateMaxWindows(1200, 600);

        System.out.println("最大可以放置的窗口数量: " + maxWindows);
    }
}
